import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Tools,Modal,Icon,TabBar,ActionSheet,FilePicker,PhotoSwipe,ActivityIndicator } from 'weaver-mobile';
import { withRouter } from 'react-router-dom';
import {getUrlParam} from '../../util/common'
import {openWorkFlow} from '../../util/pulic-func'
const getLabel = Tools.getLabel;
const weaAlert = Modal.alert;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@inject ('walletStore')
@observer
class DetailPage extends React.Component {
    constructor(props){
        super(props); 
        this.state = {
            showAll:false,
            isScroll:false,
            showImage:false,  //图片显隐
            index: 0,
        }
        this.sreenHeight = 0; 

        const {location:{search}} = this.props;
        let urlParam = getUrlParam(search);
        
        this.routeInfo = {
            id:urlParam.invoiceId,
            isViewRight:urlParam.isViewRight,
        };
    }

    static defaultProps = {
        prefixCls:"fna-invoiceDetails"
    }

    componentDidMount() {
        const { walletStore } = this.props;
        const { getInvoiceInfo,getInvoiceCreatWorkflow } = walletStore;
        this.sreenHeight = document.documentElement.clientHeight;
        getInvoiceInfo({id:this.routeInfo.id},true);
        getInvoiceCreatWorkflow({invoiceIds:this.routeInfo.id})


    }

    componentWillUnmount(){
        ActionSheet.close();
    }

    render() {
        const { walletStore,prefixCls } = this.props;
        const { isPdf,imageId,headeData,bodyData,detailsArr,showAllDetailsArr,detailsEditList,loading } = walletStore;

        let data = [];
        if(this.routeInfo.isViewRight){
            data = [
                { title: getLabel(516582,'删除') , icon:"invoice-input" , key: 0 },
            ]        
        }else{
            data=[
                { title: getLabel(516582,'删除') , icon:"invoice-input" , key: 0 },
                { title: getLabel(517379,'生成记账'), icon:"write-down-a-note" , key: 1 },
                { title: getLabel(383848,'发起报销') , icon:"initiate-reimbursement" , key: 2 },
            ]          
        }

        return (
            <div className={`${prefixCls}`}>
                <ActivityIndicator
                    toast
                    text="Loading..."
                    animating={loading}
                />            
                <header>
                    <img src={'/images/fna/fnaMobile/kou.png'} width='100%'/>
                </header>

                <div className={`${prefixCls}-body`}> 
                    <div className={`${prefixCls}-body-content`} key={'one'}>
                        {isPdf ? <a target='_blank' href={`/weaver/weaver.file.FileDownload?fileid=${imageId}&cwid=fna`}>
                                <Icon type='pdf' color={'#734AFD'}/>
                            </a>
                            // : (imageId == 0 ? <div className={'noPic'}>{'暂无图片'}</div> : <img src={`/weaver/weaver.file.FileDownload?fileid=${imageId}&cwid=fna`} />)}
                            : (imageId == 0 ? 
                                <div className={'noPic'}>{'暂无图片'}</div> 
                                : 
                                <FilePicker
                                    className={'fna-detailPage-filePicker'}
                                    listType="img"
                                    files={[{id: '2122',url: `/weaver/weaver.file.FileDownload?fileid=${imageId}&cwid=fna`}]}
                                    onItemClick={this.onItemClick}
                                />
                                )}
                        {headeData.map( i=>{
                            return (
                                <div className={'fna-invoiceDetails-head-div'} key={Math.random()}>
                                    <div className={'fna-invoiceDetails-head-div-left'}><span>{i.title}</span>:</div>
                                    <div className={'fna-invoiceDetails-head-div-right'}><span>{i.money}</span></div>
                                </div>
                            )
                        })}
                        <div><img src={'/images/fna/fnaMobile/split-line-02.png'} width='100%'/></div>
                        {bodyData.map( items=>{
                            let details = this.state.showAll ? showAllDetailsArr : detailsArr;

                            return(
                                <div key={items.key ? items.key : 'invoiceDetails'} className={'invoiceDetails'}>
                                    <div>{items.caption}</div>
                                    <div className={'fixHeight'}>
                                        {details.map(i=>{
                                            let _class = i.key ? this.getClass(i.key) : '';
                                            let comment;
                                            if(i.show){
                                                comment = 
                                                    <div className={'fna-invoiceDetails-content-div'} key={i.id}>
                                                        <div className={'fna-invoiceDetails-content-div-left'}>{i.title}：</div>
                                                        <div className={`fna-invoiceDetails-content-div-right ${_class}`}>{i.value}</div>
                                                    </div>
                                            }else {
                                                comment = ''
                                            }

                                            return comment
                                            
                                        })}

                                        {JSON.stringify(detailsEditList) != '{}' && this.state.showAll &&
                                            <div className={'editList'}>
                                                <table className={detailsEditList.col == '5' ? 'editList_5' : 'editList_7'}>
                                                    <tbody>
                                                        <tr>
                                                            <td colSpan={'5'}>{detailsEditList.type}</td>
                                                        </tr>
                                                    
                                                        {
                                                            detailsEditList.conditions.map(c =>{
                                                                return (
                                                                    <tr key={c.key}>
                                                                        {c.items.map(f =>(
                                                                            <td>{f.title}</td>
                                                                        ))}
                                                                    </tr>
                                                                )
                                                            }) 
                                                        }
                                                    </tbody>
                                                </table>
                                            </div>
                                        }
                                    </div>


                                        
                                    {this.state.showAll ? 
                                        <div className={'showAll'} onClick={()=>{this.getAllShow(false);}}>{getLabel(517380,'收起全部')}</div> 
                                        : 
                                        <div className={'showAll'} onClick={()=>{this.getAllShow(true);}}>{getLabel(84533,'展开全部')}</div>
                                    }
                                        
                                    
                                </div>
                               
                            )
                            
                        })}
                        
                        
                    </div>

                    <div className="fna-bar">
                        <TabBar
                            barTintClassName={'fna-invoiceDetails-bar-tint-color'}
                            unselectedTintColor='#f00' //未选中的字体颜色
                            tintColor='#f00' //选中的字体颜色
                            // tabBarPosition="bottom"
                            key={'tabBar'}
                        >
                            {
                                data.map(item=>{
                                    return (
                                        <TabBar.Item
                                            title={item.title}
                                            key={item.key}
                                            icon={<Icon type={item.icon}/>}
                                            selectedIcon={<Icon type={item.icon}/> }
                                            // selected={this.state.selectedKey === item.key}
                                            onPress = {()=>{this.onPress(item.key)}}
                                        />
                                    )
                                })
                            }
                        </TabBar>
                        
                    </div>                    
                   
                    
                </div>
            
            </div>
        )
    }

    toArr = (arrayLike) =>{
        let arr = [];
        for (let key in arrayLike) {
            arr.push(arrayLike[key]);  
        }
        return arr;
    }

    onItemClick = (file, index, files) => {
        this.setState({
          showImage: true,
          index,
        });
        PhotoSwipe.showImage(files, index);
    }    

    onPress = (key) =>{
        const {walletStore,history} = this.props;
        const { getInvoiceCreatWorkflow } = walletStore;
        
        if(key == 0){
            weaAlert(getLabel(517381,'确定要删除该发票吗？'), getLabel(517382,'注意：删除后无法恢复'), [
                { text: getLabel(516571,'取消'), onPress: () => {}, style: 'default' },
                { text: getLabel(826,'确定'), onPress: () => {this.doDelete()} },
            ]);


        }else if(key == 1){//生成记账
            this.props.history.push(`/remember?invoiceIds=${this.routeInfo.id}`)
        }else if(key == 2){//发起报销
            const { workflowSelect,invoiceCreatWorkflow } = walletStore;

            let allMonth = workflowSelect;
            ActionSheet.showActionSheetWithOptions({
                options: allMonth,
                cancelButtonIndex: allMonth.length - 1,
                // destructiveButtonIndex: BUTTONS.length - 2,
                // title: '请选择月份',
                // message: '请选择月份',
                maskClosable: true,
                'data-seed': 'logId',
                wrapProps,
            },  
            (buttonIndex) => {
                if(buttonIndex != allMonth.length - 1){
                    let params = {
                        workflowId:workflowSelect[buttonIndex].id,
                        id:this.routeInfo.id
                    }

                    invoiceCreatWorkflow(params,(value)=>{
                        openWorkFlow('view',value.requestId);
                    })
                }
                    
            });    
            
        }


    }

    getAllShow = (bool) =>{
        const {walletStore} = this.props;
        const {detailsArr,setDetailsArr,setBodyData,bodyData} = walletStore;

        this.setState({showAll:bool})
    }

    bindHandleScroll = (e) =>{
        // console.log('e',e.target)
    }

    doDelete = (value) =>{
        const {walletStore,reset_tjfj} = this.props;
        const {doDeleteInvoice} = walletStore;
        let params = {
            id:this.routeInfo.id
        }
        doDeleteInvoice(params,()=>{
            reset_tjfj && reset_tjfj();
            this.props.history.go(-1)
        });

    }
    
    getClass = (key) =>{
        let className = '';
        if(key == 'checkStatus'){
            className = 'fna-textColor-red'
        }
        return className;
    }
    

}

export default DetailPage;